package thesis.filesharing.web.validator;

import java.util.Date;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.web.viewmodel.CreateExerciseViewModel;

public class CreateExerciseValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return CreateExerciseViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		
		CreateExerciseViewModel model = (CreateExerciseViewModel) target;
		
		if ("NONE".equalsIgnoreCase(model.getClassKey())) {
			errors.rejectValue("classKey", "classKey.required");
		}
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "exerciseTitle", "exerciseTitle.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "tags", "tags.required");
		
		if (model.getTags() != null && !"".equals(model.getTags())) {
			String tags = model.getTags().trim();
			String[] tagList = tags.split(",");
			int count = 0;
			for (String t : tagList) {
				t = t.trim();
				if ("".equals(t)) {
					errors.rejectValue("tags", "tags.invalidFormat");
					break;
				} else {
					count++;
				}
			}
			if (count > 4) {
				errors.rejectValue("tags", "tags.exceedLimit");
			}
		}
		
		if ("NONE".equalsIgnoreCase(model.getExerciseType())) {
			errors.rejectValue("exerciseType", "exerciseType.required");
		}
		
		if ("NONE".equalsIgnoreCase(model.getGroupExercise())) {
			errors.rejectValue("groupExercise", "groupExercise.required");
		}
		
		if (model.getDeadline() != null && new Date().after(model.getDeadline())) {
			errors.rejectValue("deadline", "deadline.incorrect");
		}
	}
}
